package online.inote.naruto.utils.http;

import okhttp3.OkHttpClient;

import java.util.concurrent.TimeUnit;

/**
 * @description Http client
 * @author gaopengsui@creditease.cn
 * @date 2021/10/08 3:33 下午
 */
public class Http {

  private OkHttpClient client;
  private ResultConvertor convertor;

  public Http(Builder builder) {
    this.buildInstance(builder);
  }

  private void buildInstance(Builder builderProps) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 设置默认主机验证规则
    builder.hostnameVerifier((hostname, session) -> true);
    // 添加拦截器
    builder.addInterceptor(new LogInterceptor());

    builder.connectTimeout(builderProps.connectTimeout, TimeUnit.MILLISECONDS);
    builder.writeTimeout(builderProps.writeTimeout, TimeUnit.MILLISECONDS);
    builder.readTimeout(builderProps.readTimeout, TimeUnit.MILLISECONDS);

    this.client = builder.build();
    this.convertor = builderProps.convertor;
  }

  public SyncRequest sync() {
    return SyncRequest.builder().client(this.client).convertor(convertor).build();
  }

  public static Builder builder() {
    return new Builder();
  }

  public static class Builder {
    /** 连接超时时间 默认超时时间:3秒(单位:毫秒) */
    private long connectTimeout = 5 * 1000;
    /** 写数据超时时间 默认超时时间:3秒(单位:毫秒) */
    private long writeTimeout = 5 * 1000;
    /** 读数据超时时间 默认超时时间:3秒(单位:毫秒) */
    private long readTimeout = 5 * 1000;
    /** 读数据超时时间 默认超时时间:3秒(单位:毫秒) */
    private ResultConvertor convertor = new DefaultResultConvertor();

    public Builder connectTimeout(long connectTimeout) {
      this.connectTimeout = connectTimeout;
      return this;
    }

    public Builder writeTimeout(long writeTimeout) {
      this.writeTimeout = writeTimeout;
      return this;
    }

    public Builder readTimeOut(long readTimeout) {
      this.readTimeout = readTimeout;
      return this;
    }

    public Builder convertor(ResultConvertor convertor) {
      this.convertor = convertor;
      return this;
    }

    public Http build() {
      return new Http(this);
    }
  }
}
